package com.mg.plugincqamg.common;

import com.mg.plugincqamg.entity.StationData;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DataFormatter {
    public static void formatStationData(List<String> stationDataList, Map<String,String> headerIndex, Map<String,List<StationData>> stationDataMap) {
        String realHeader = stationDataList.get(0);
        int realStationIndex = findDataIndex(realHeader, headerIndex.get("StationId"));
        int realLatIndex = findDataIndex(realHeader, headerIndex.get("Lat"));
        int realLonIndex = findDataIndex(realHeader, headerIndex.get("Lon"));
        int realDateIndex = findDataIndex(realHeader, headerIndex.get("Date"));
        int realTempIndex = findDataIndex(realHeader, headerIndex.get("Temp"));
        int realER24Index = findDataIndex(realHeader, headerIndex.get("ER24"));
        int realSSHIndex = findDataIndex(realHeader, headerIndex.get("SSH"));

        for (int i = 2; i < stationDataList.size(); i++) {
            String[] data = stationDataList.get(i).split(",");
            String stationId = data[realStationIndex];
            StationData stationData = new StationData();
            stationData.setStationId(stationId);
            stationData.setLat(Double.parseDouble(data[realLatIndex]));
            stationData.setLon(Double.parseDouble(data[realLonIndex]));
            stationData.setDate(data[realDateIndex]);
            stationData.setTemp(Double.parseDouble(data[realTempIndex]));
            stationData.setEr24(Double.parseDouble(data[realER24Index]));
            stationData.setSsh(Double.parseDouble(data[realSSHIndex]));

            if (stationDataMap.keySet().contains(stationId)) {
                stationDataMap.get(stationId).add(stationData);
            } else {
                List<StationData> dataList = new ArrayList<StationData>();
                dataList.add(stationData);
                stationDataMap.put(stationId, dataList);
            }
        }
    }

    private static int findDataIndex(String realHeader, String ele) {
        String[] data = realHeader.split(",");
        for (int i = 0; i < data.length; i++) {
            if (data[i].equalsIgnoreCase(ele)) {
                return i;
            }
        }
        return -1;
    }
}
